package com.edu.controller;

import org.springframework.core.io.ResourceEditor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.spi.http.HttpHandler;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class DownloadsController {

    @RequestMapping("/download")
    public void down(HttpServletRequest request, HttpServletResponse response){
        //获取真实路径
        String realPath = request.getServletContext().getRealPath("/file/ApplicationContext.xml");
        //创建一个file 表示一个要被下载的路径
        File file = new File(realPath);
        FileInputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //创建输入流来读取
            inputStream = new FileInputStream(file);
            //设定响应的格式 告知输出流的格式以附件的形式打开
            response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(file.getName(),"UTF-8"));
            //获取用于向客户端 返回数据的 输出流、
            outputStream = response.getOutputStream();

            byte[] bytes =new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
            }

            inputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/download2")
    public ResponseEntity<byte[]> down2(HttpServletRequest request) throws IOException {
        //获取真实路径
        String realPath = request.getServletContext().getRealPath("/file/ApplicationContext.xml");
        //创建一个file对象
        File file = new File(realPath);
        //创建下载流
        FileInputStream inputStream = new FileInputStream(file);
        //创建http头文件
        HttpHeaders httpHeaders = new HttpHeaders();
        //头文件
        httpHeaders.set("content-disposition","attachment;fileName="+ URLEncoder.encode(file.getName(),"UTF-8"));

        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        return new ResponseEntity<byte[]>(bytes,httpHeaders, HttpStatus.OK);

    }
}
